#!/bin/sh -f
# $Id: httpd 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

# Program name
PROG=`basename $0`

# UID value
UID=`id -u`

# Globals
HTTPD=`which apachectl`
RM="/bin/rm -f"
SED=`which sed`
AWK=`which awk`

usage () {
   printf "${PROG} options [ commands ]\n"
   printf "options: \n"
   printf " -h [ prints this help ]\n"
   printf "commands: \n"
   printf "\t start     [ Start HTTP daemon ]\n"
   printf "\t stop      [ Stop HTTP daemon ]\n"
   printf "\t status    [ Status of HTTP daemon ]\n"
   printf "\t restart   [ Restart HTTP daemon ]\n"
   exit 1
}
count=0
httpd_pid=
for value in `ps aux | egrep [h]ttpd: | $SED -En 's/^[a-z_]+ +([0-9]+).*/\1/p'`;
do
   httpd_pid[${count}]=${value}
   count=`expr $count + 1`
done

count=${#httpd_pid[@]}

start_httpd () {
   ${HTTPD} startssl
}

stop_httpd () {
   ${HTTPD} stop
}

status_httpd () {
   index=0
   HTTPD_PID=
   until [ ${index} -ge ${count} ]; do
      HTTPD_PID="${httpd_pid[${index}]} ${HTTPD_PID}"
      index=`expr $index + 1`
   done

   echo "${PROG} running, pid(s): ${HTTPD_PID}"
}

# If we do not have enough arguments, then 
if [ $# -lt 1 ]; then
   usage
else 
   while getopts h arg; do
      case ${arg} in
         h)
            usage
            ;;

         *)
            usage
            ;;
      esac
   done

   if [ ${UID} -ne 0 ]; then
      printf "${PROG}: needs to have root privileges\n"
      exit 1
   fi

   arg=`echo $* | awk '{ print $NF; }'`

   case ${arg} in
      start)
         start_httpd
         ;;

      stop)
         stop_httpd
         ;;

      status)
         status_httpd
         ;;

      restart)
         stop_httpd
         sleep 5
         start_httpd
         ;;

      *)
         usage
         ;;

   esac
fi
